package com.yanqu.road.server.manger.activity.huashigang;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangActivityEventConfig;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangFloorConfig;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangNewConfig;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.logic.activity.HuaShiGangLogic;
import com.yanqu.road.logic.bussiness.activity.HuaShiGangActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.pb.huashigang.HuaShiGangProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.huashigang.HuaShiGangModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.scene.SceneMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wpj
 * @Date 2020/10/4
 */
public class HuaShiGangMgr extends TempMgr {
    /**
     * 配置项
     */
    public static int isUseMount; // 是否开启宝马
    public static int mountCost;  // 解锁宝马消耗元宝数量
    public static List<Integer> spreadWealthConfig = new ArrayList<>(); //散财参数配置

    public static HuaShiGangNewConfig newConfig;

    public static ActivityInfo activityInfo;
    public static Map<Integer, HuaShiGangActivityEventConfig> huaShiGangActivityEventConfigMap;
    public static Map<Integer, HuaShiGangFloorConfig> integerHuaShiGangFloorConfigMap;

    // ==============================================================

    public static List<HuaShiGangProto.EventConfigEntity> getEventsPb(String language) {
        List<HuaShiGangProto.EventConfigEntity> builderList = new ArrayList<>();
        for (HuaShiGangActivityEventConfig config : getHuaShiGangActivityEventConfigMap().values()) {
            builderList.add(getEventPb(language, config));
        }

        return builderList;
    }

    private static HuaShiGangProto.EventConfigEntity getEventPb(String language, HuaShiGangActivityEventConfig config) {
        HuaShiGangProto.EventConfigEntity.Builder builder = HuaShiGangProto.EventConfigEntity.newBuilder();
        builder.setEventId(config.getEventId());
        builder.setEventType(config.getEventType());
        builder.setNpcId(config.getNpcId());
        builder.setIcon(config.getIcon());
        builder.setWeight(config.getWeight());
        builder.setName(ServerLanguageMgr.getContent(config.getName(), language));
        builder.setDesc(ServerLanguageMgr.getContent(config.getDesc(), language));
        builder.setRewards(config.getRewards());
        builder.setParamList(config.getParamList());
        return builder.build();
    }

    /**
     * 是否在允许操作的时间内
     *
     * @param activityInfo
     * @return
     */
    public static boolean inOperateTime(ActivityInfo activityInfo) {
        if (ActivityMgr.activityInTime(activityInfo)) {
            // 0点到现在的间隔，毫秒
            long now = System.currentTimeMillis();
            long zeroTime = DateHelper.getZeroTimeStamp(now);
            long subTime = now - zeroTime;
            // 比较
            List<Long> operationTimeList = newConfig.getOperationTimeList();
            if (subTime > operationTimeList.get(0) && subTime < operationTimeList.get(1)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取活动状态
     *
     * @param player
     * @return
     */
    public static int getActivityInfoRet(GamePlayer player) {
        if (player.isRequestToFast()) {
            return GameErrorCode.E_REQUEST_TOO_FAST;
        }
        if (activityInfo == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        return 0;
    }

    public static Map<Integer, HuaShiGangFloorConfig> getIntegerHuaShiGangFloorConfigMap() {
        return integerHuaShiGangFloorConfigMap;
    }

    public static Map<Integer, HuaShiGangActivityEventConfig> getHuaShiGangActivityEventConfigMap() {
        return huaShiGangActivityEventConfigMap;
    }

    public static void setHuaShiGangActivityEventConfigMap(Map<Integer, HuaShiGangActivityEventConfig> huaShiGangActivityEventConfigMap) {
        HuaShiGangMgr.huaShiGangActivityEventConfigMap = huaShiGangActivityEventConfigMap;
    }

    public static void reloadActivityData(Map<Integer, ActivityInfo> huaShiGangActivityInfoMap) {
        getLogger().info("reload HuaShiGangMgr start");
        ActivityInfo inTimeActivity = null;
        for (ActivityInfo activityInfo : huaShiGangActivityInfoMap.values()) {
            if (ActivityMgr.activityInShowTime(activityInfo)) {
                inTimeActivity = activityInfo;
                break;
            }
        }
        if (inTimeActivity != null) {
            huaShiGangActivityEventConfigMap = HuaShiGangActivityBusiness.getHuaShiGangActivityEventConfig(inTimeActivity.getActivityId());
            HuaShiGangLogic.parseEventConfigParam(huaShiGangActivityEventConfigMap.values());
            integerHuaShiGangFloorConfigMap = HuaShiGangActivityBusiness.getHuaShiGangFloorConfig(inTimeActivity.getActivityId());
            loadConfig(inTimeActivity.getActivityId());
        }
        activityInfo = inTimeActivity;
        playerReloadActivity();
        SceneMgr.initActivity(activityInfo);
    }

    /**
     * 加载活动配置
     * @param activityId 活动id
     */
    private static void loadConfig(int activityId) {
        Map<String, ActivityConfig> configMap = NormalActivityMgr.getActivityConfigMap(activityId);
        isUseMount = configMap.get(eActivityConfigType.HUASHIGUANG_IS_USE_MOUNT.getName()).getIntValue();
        mountCost = configMap.get(eActivityConfigType.HUASHIGUANG_MOUNT_CONSUME.getName()).getIntValue();
        String[] split = configMap.get(eActivityConfigType.HUASHIGUANG_SPREAD_WEALTH_CONFIG.getName()).getValue().split("\\|");
        for (String s : split) {
            spreadWealthConfig.add(Integer.parseInt(s));
        }
        loadNewConfig(activityId);
    }

    private static void loadNewConfig(int activityId) {
        Map<String, ActivityConfig> configMap = NormalActivityMgr.getActivityConfigMap(activityId);
        HuaShiGangNewConfig tmpConfig = new HuaShiGangNewConfig();
        tmpConfig.setScoreItemId(configMap.get(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName()).getIntValue());
        tmpConfig.setDispatchItemId(configMap.get(eActivityConfigType.HUASHIGUANG_DISPATCH_ITEM_ID.getName()).getIntValue());
        tmpConfig.setOperationTimeList(configMap.get(eActivityConfigType.HUASHIGUANG_OPERATION_TIME.getName()).getIntListValue("\\|")
                .stream().mapToLong(item -> item * DateHelper.MINUTE_MILLIONS).boxed().collect(Collectors.toList()));
        List<List<Integer>> stageTimeParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(configMap.get(eActivityConfigType.HUASHIGUANG_STAGE_TIME.getName()).getValue(), "\\|")) {
            stageTimeParam.add(StringUtils.stringToIntegerList(str, ";"));
        }
        tmpConfig.setStageTimeList(stageTimeParam);
        tmpConfig.setDayUnitNum(configMap.get(eActivityConfigType.HUASHIGUANG_DAY_UNIT_NUM.getName()).getIntValue());
        tmpConfig.setUnitModeNum(configMap.get(eActivityConfigType.HUASHIGUANG_DAY_MODE_NUM.getName()).getIntValue());
        tmpConfig.setServerBaseHp(configMap.get(eActivityConfigType.HUASHIGUANG_ONE_SERVER_BASE_HP.getName()).getLongValue());
        List<List<Integer>> serverHpParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(configMap.get(eActivityConfigType.HUASHIGUANG_SERVER_HP_ENLARGE.getName()).getValue(), "\\|")) {
            serverHpParam.add(StringUtils.stringToIntegerList(str, ";"));
        }
        tmpConfig.setServerHpEnlarge(serverHpParam);
        List<List<Integer>> monsterHpParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(configMap.get(eActivityConfigType.HUASHIGUANG_MONSTER_HP_ENLARGE.getName()).getValue(), "\\|")) {
            monsterHpParam.add(StringUtils.stringToIntegerList(str, ";"));
        }
        tmpConfig.setMonsterHpEnlarge(monsterHpParam);
        List<List<Integer>> scoreCalcParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(configMap.get(eActivityConfigType.HUASHIGUANG_SCORE_CALC_PARAM.getName()).getValue(), "\\|")) {
            scoreCalcParam.add(StringUtils.stringToIntegerList(str, ";"));
        }
        tmpConfig.setScoreCalcParam(scoreCalcParam);
        List<List<Integer>> pointMonsterNumParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(configMap.get(eActivityConfigType.HUASHIGUANG_POINT_MONSTER_NUM.getName()).getValue(), "\\|")) {
            pointMonsterNumParam.add(StringUtils.stringToIntegerList(str, ";"));
        }
        tmpConfig.setPointMonsterNum(pointMonsterNumParam);
        tmpConfig.setNormalDispatchCost(configMap.get(eActivityConfigType.HUASHIGUANG_NORMAL_DISPATCH_COST_NUM.getName()).getIntListValue("\\|"));
        tmpConfig.setBossDispatchCost(configMap.get(eActivityConfigType.HUASHIGUANG_BOSS_DISPATCH_COST_NUM.getName()).getIntListValue("\\|"));
        tmpConfig.setHelpModeDistance(configMap.get(eActivityConfigType.HUASHIGUANG_TRIGGER_HELP_MODE_DISTANCE.getName()).getIntValue());
        List<List<Integer>> helpLengthParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(configMap.get(eActivityConfigType.HUASHIGUANG_HELP_LENGTH.getName()).getValue(), "\\|")) {
            helpLengthParam.add(StringUtils.stringToIntegerList(str, ","));
        }
        tmpConfig.setHelpLength(helpLengthParam);
        tmpConfig.setHelpAddition(configMap.get(eActivityConfigType.HUASHIGUANG_HELP_ADDITION.getName()).getIntValue());
        if (configMap.containsKey(eActivityConfigType.HUASHIGUANG_DIG_PASS_BOX.getName())){
            tmpConfig.setDigPassBox(configMap.get(eActivityConfigType.HUASHIGUANG_DIG_PASS_BOX.getName()).getIntValue());
        }
        if (configMap.containsKey("HUASHIGUANG_DIG_PASS_BOX_CONTENT")) {
            List<List<Property>> list = PropertyHelper.parseNewStringToPropertyList(configMap.get("HUASHIGUANG_DIG_PASS_BOX_CONTENT").getValue());
            tmpConfig.setDigPassRewardList(list);
        }
        tmpConfig.setEliteKillRankScore(configMap.get(eActivityConfigType.HUASHIGUANG_ELITE_KILL_RANK_SCORE.getName()).getIntListValue(","));
        tmpConfig.setGoldKeyId(configMap.get(eActivityConfigType.HUASHIGUANG_GOLD_KEY_ID.getName()).getIntValue());
        tmpConfig.setDigItemId(configMap.get(eActivityConfigType.HUASHIGUANG_DIG_ITEM_ID.getName()).getIntValue());
        tmpConfig.setAttackDigItemGetParam(configMap.get(eActivityConfigType.HUASHIGUANG_DIG_ITEM_GET_PARAM.getName()).getIntListValue(";"));
        tmpConfig.setBossNoticeItemId(configMap.get(eActivityConfigType.HUASHIGUANG_KILL_BOSS_NOTICE_ITEM.getName()).getIntListValue("\\|"));
        tmpConfig.setRmbMallTime(configMap.get(eActivityConfigType.HUASHIGUANG_RMB_MALL_TIME.getName()).getLongValue() * DateHelper.MINUTE_MILLIONS);
        String hpParam1 = ActivityHelper.getActivityConfigValue(configMap, eActivityConfigType.HUASHIGUANG_BOSS_HP_PARAM_1);
        tmpConfig.setUserFloorEnlarge(StringUtils.stringToIntegerList(hpParam1, "\\|"));
        String hpParam2 = ActivityHelper.getActivityConfigValue(configMap, eActivityConfigType.HUASHIGUANG_BOSS_HP_PARAM_2);
        List<List<Integer>> bossHpEnlargeParam = new ArrayList<>();
        for (String str : StringUtils.stringToStringList(hpParam2, "#")) {
            bossHpEnlargeParam.add(StringUtils.stringToIntegerList(str, "\\|"));
        }
        tmpConfig.setBossHpEnlarge(bossHpEnlargeParam);
        if (configMap.containsKey(eActivityConfigType.HUASHIGUANG_STAGE_TWO_UNIT_NUM_LEAST.getName())) {
            tmpConfig.setStage2MinUnitCount(configMap.get(eActivityConfigType.HUASHIGUANG_STAGE_TWO_UNIT_NUM_LEAST.getName()).getIntValue());
        }
        String hpParam3 = ActivityHelper.getActivityConfigValue(configMap, eActivityConfigType.HUASHIGUANG_BOSS_HP_PARAM_3);
        tmpConfig.setBossHpParam3(StringUtils.stringToIntegerList(hpParam3, "\\|"));

        if (configMap.containsKey("AUTO_TEND_NUM")){
            String autoTendNum = configMap.get("AUTO_TEND_NUM").getValue();
            tmpConfig.setAutoOperateConfig(StringUtils.stringToIntegerList(autoTendNum, ";"));
        }else {
            tmpConfig.setAutoOperateConfig(new ArrayList<>());
        }

        newConfig = tmpConfig;
    }

    private static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(action -> {
            action.getModule(HuaShiGangModule.class).sendConfigToClient();
        });
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static void setActivityInfo(ActivityInfo activityInfo) {
        HuaShiGangMgr.activityInfo = activityInfo;
    }

    /**
     * 打开箱子
     *
     * @param player
     * @param boxId
     * @param reward
     * @param stat
     */
    public static void openBox(GamePlayer player, int boxId, String reward, int stat, int num) {
        // 恢复预扣除的道具
        String openCost = huaShiGangActivityEventConfigMap.get(boxId).getOpenCostKeyId() + "=" + num;
        player.getModule(PreReduceModule.class).restorePreReduce(openCost);
        // 开箱成功才扣除钥匙
        if (stat == 0) {
            player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(openCost), eLogMoneyType.HuaShiGang, eLogMoneyType.HuaShiGangOpenBox);
            player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.HuaShiGang, eLogMoneyType.HuaShiGangOpenBox);
        }
        HuaShiGangProto.OpenBoxRespMsg.Builder builder = HuaShiGangProto.OpenBoxRespMsg.newBuilder();
        builder.setRet(stat);
        builder.setReward(reward);
        player.sendPacket(ClientProtocol.U_HUA_SHI_GANG_OPEN_BOX, builder);
    }

    /**
     * 解锁交通工具
     *
     * @param player
     * @param transportId
     * @param ret
     */
    public static void UnLockTransport(GamePlayer player, int transportId, int ret) {
        //解锁消耗
        String cost = GameConfig.GAME_MONEY_INGOTS + "=" + HuaShiGangMgr.mountCost;
        //恢复预扣除项
        player.getModule(PreReduceModule.class).restorePreReduce(cost);
        //解锁成功才扣除
        if (ret == 0) {
            player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(cost), eLogMoneyType.HuaShiGang, eLogMoneyType.HuaShiGangUnLockTransport);
        }
        HuaShiGangProto.UnLockTransPortRespMsg.Builder builder = HuaShiGangProto.UnLockTransPortRespMsg.newBuilder();
        builder.setRet(ret);
        player.sendPacket(ClientProtocol.U_HUA_SHI_GANG_UNLOCK_TRANSPORT, builder);
    }

    /**
     * 获取层数对应的配置
     *
     * @param floor
     * @return
     */
    public static HuaShiGangFloorConfig getHuaShiGangFloorConfig(int floor) {
//        if (integerHuaShiGangFloorConfigMap == null) {
//            return null;
//        }
//        HuaShiGangFloorConfig config = integerHuaShiGangFloorConfigMap.get(floor);
//        if (config == null) {
//            // 不存在则直接取最高
//            List<Integer> list = new ArrayList<>(integerHuaShiGangFloorConfigMap.keySet());
//            Collections.sort(list);
//            int floorNum = list.get(list.size() - 1);
//            config = integerHuaShiGangFloorConfigMap.get(floorNum);
//        }
//        return config;
        return integerHuaShiGangFloorConfigMap.get(floor);
    }

    /**
     * 钥匙预扣除
     *
     * @param player
     * @param boxId
     */
    public static void preReduceKey(GamePlayer player, int boxId, int num) {
        player.getModule(PreReduceModule.class).preReduce(huaShiGangActivityEventConfigMap.get(boxId).getOpenCostKeyId() + "=" + num);
    }

    /**
     * 解锁交通工具消耗预扣除
     *
     * @param player
     * @param cost
     */
    public static void preReduceUnLockTransportCost(GamePlayer player, String cost) {
        player.getModule(PreReduceModule.class).preReduce(cost);
    }

    /**
     * 领取花石纲送财奖励
     * @param earnSpeed  领取奖励的玩家赚速
     * @return Property
     */
    public static Property getDisperseGoldReward(BigInteger earnSpeed) {
        RandomHelper r = new RandomHelper();
        //银两奖励
        int totalSilver = r.next(spreadWealthConfig.get(0), spreadWealthConfig.get(1));
        BigInteger silver = earnSpeed.multiply(BigInteger.valueOf(totalSilver));

        //元宝奖励
        int IngotsNum = r.next(spreadWealthConfig.get(2), spreadWealthConfig.get(3));

        Property property = new Property();
        property.addProperty(GameConfig.GAME_MONEY_SILVER, silver);
        property.addProperty(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(IngotsNum));
        return property;
    }

    /**
     * 根据活动子类型获取活动积分id
     * @param
     * @return
     */
    public static int getHuaShiGangScoreId() {
        return newConfig.getScoreItemId();
    }

    public static HuaShiGangNewConfig getNewConfig() {
        return newConfig;
    }

    /**
     * 根据活动子类型获取活动出战令id
     * @param
     * @return
     */
    public static int getHuaShiGangTokenId() {
        return newConfig.getDispatchItemId();
    }

    /**
     * 根据活动子类型获取活动出战令id
     * @param
     * @return
     */
    public static int getHuaShiGangGoldKeyId() {
        return newConfig.getGoldKeyId();
    }

    public static int getChildType() {
        if (activityInfo == null) {
            return 0;
        }
        return activityInfo.getChildType();
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }
}
